<template>
  <div class="tableHeader">
    <a-row :gutter="[16, 16]" class="search">
      <a-col :span="4">
        <a-input v-model:value="SearchInfo.searchFiled" placeholder="模糊搜索"/>
      </a-col>
      <a-col :span="5">
        <a-range-picker v-model:value="SearchInfo.time">
          <template #dateRender="{ current }">
            <div :style="getCurrentStyle(current)" class="ant-picker-cell-inner">
              {{ current.date() }}
            </div>
          </template>
        </a-range-picker>
      </a-col>
      <a-col :span="4" class="btn">
        <a-button :icon="h(SearchOutlined)" type="primary"
        >搜索
        </a-button
        >
        <a-button :icon="h(RedoOutlined)">重置</a-button>
      </a-col>
    </a-row>
    <a-row class="buttons">
      <a-button type="primary" @click="openModal('add')">新增</a-button>
      <a-button danger>删除</a-button>
    </a-row>
  </div>
  <a-table :columns="columns" :data-source="data"
           :pagination="false"
           :row-selection="rowSelection"
           :scroll="{ y: 400 }" style="height: calc(100vh - 220px)">
    <template #bodyCell="{ column, record }">
      <template v-if="column.key==='icon'">
        <component :is="iconObj[record.icon]"/>
      </template>
      <template v-if="column.key === 'action'">
        <span style="display: flex; align-items: center;gap: 15px">
          <a-button type="primary" @click="openModal('edit',record)">
            <template #icon>
              <EditOutlined/>
            </template>
          </a-button>
          <a-popconfirm
              cancel-text="取消"
              ok-text="删除"
              title="是否删除该菜单?"
              @confirm="confirmDel(record)"
          >
              <a-button danger>
                <template #icon>
                  <DeleteOutlined/>
                </template>
              </a-button>
          </a-popconfirm>
        </span>
      </template>
    </template>
  </a-table>
  <Modal ref="ModalRef" :title="title" style="width: 580px">
    <slot>
      <a-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          style="padding-top: 15px"
      >
        <a-form-item ref="menu_type" label="菜单类型" name="menu_type">
          <a-radio-group v-model:value="formState.menu_type" button-style="solid">
            <a-radio-button value="M">目录</a-radio-button>
            <a-radio-button value="C">菜单</a-radio-button>
            <a-radio-button value="F">按钮</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item ref="icon" label="菜单图标" name="icon">
          <a-input v-model:value="formState.icon" placeholder="请选择菜单图标"/>
        </a-form-item>
        <a-form-item ref="label" label="菜单名称" name="label">
          <a-input v-model:value="formState.label" placeholder="请输入菜单名称"/>
        </a-form-item>
        <a-form-item ref="perms" label="权限标识" name="perms">
          <a-input v-model:value="formState.perms" placeholder="请输入权限标识"/>
        </a-form-item>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item ref="path" label="路由地址" name="path">
              <a-input v-model:value="formState.path" placeholder="请输入菜单路由地址"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item ref="name" label="菜单顺序" name="name">
              <a-input-number id="inputNumber" v-model:value="formState.order_num" :max="10" :min="1"/>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row v-if="formState.menu_type==='C'" :gutter="24">
          <a-col :span="12">
            <a-form-item ref="name" label="组件别名" name="name">
              <a-input v-model:value="formState.name" placeholder="请输入菜单别名"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item ref="component" label="组件地址" name="component">
              <a-input v-model:value="formState.component" placeholder="请输入菜单组件地址"/>
            </a-form-item>
          </a-col>
        </a-row>


        <a-form-item v-if="formState.menu_type==='C'" ref="isShow" label="是否显示菜单" name="isShow">
          <a-radio-group v-model:value="formState.isShow">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="2">不显示</a-radio>
          </a-radio-group>
        </a-form-item>


        <a-form-item ref="parent_id" label="上级类目" name="parent_id">
          <a-select v-model:value="formState.parent_id" placeholder="请选择菜单上级类目">
            <a-select-option value="0">顶级类目</a-select-option>
            <a-select-option v-for="(item,index) in MenusParentList" :value="item.id">{{ item.label }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <div style="width: 100%;display: flex;align-items: center;justify-content: end;gap: 15px">
            <a-button style="margin-left: 10px" @click="openModal">取消</a-button>
            <a-button type="primary" @click="onSubmit">创建</a-button>
          </div>
        </a-form-item>
      </a-form>
    </slot>
  </Modal>
</template>
<script setup>
import Modal from "@/components/Modal/index.vue";
import {computed, h, onMounted, reactive, ref, toRaw} from 'vue';
import {
  AppstoreOutlined,
  CodeOutlined,
  DeleteOutlined,
  EditOutlined,
  PartitionOutlined,
  ProfileOutlined,
  RedoOutlined,
  RestOutlined,
  SearchOutlined,
  SettingOutlined
} from "@ant-design/icons-vue";
import {addMenus, delMenus, get_menus, updateMenus,} from "@/api/auth.js";
import {message} from "ant-design-vue";

const iconObj = {
  ProfileOutlined,
  PartitionOutlined,
  RestOutlined,
  SettingOutlined,
  CodeOutlined,
  AppstoreOutlined,
};

const formRef = ref();

// 头部搜索表单
const ModalRef = ref('')

const SearchInfo = ref({
  searchFiled: "",
  time: []
})


// 菜单列表
const MenusParentList = computed(() => {
  if (data.value) {
    return data.value.filter(item => item.parent_id === 0 && item.label !== '首页')
  }
})


// 新增和编辑表单相关
let title = ref('新增菜单')

let id = ref('')

let formState = reactive({
  label: '',
  name: '',
  menu_type: 'M',
  path: '',
  component: '',
  icon: '',
  parent_id: '0',
  order_num: 999,
  perms: '',
  isShow: 1
});

// 新增和编辑表单提交
const onSubmit = () => {
  const type = title.value === '新增菜单' ? 'add' : 'edit'
  formRef.value
      .validate()
      .then(async () => {
        let res = await requestData(type)
        if (!res) return;
        if (res.status === 400) message.error(res.data)
        if (res.status === 200) message.success(res.data)
        // 重新请求数据
        await getAllMenus()
        openModal()
      })
      .catch(error => {
        console.log('error', error);
      });
};

// 提交请求
const requestData = async (type = 'add') => {
  let info = toRaw(formState)
  if (type === 'add') {
    return await addMenus(info);
  }
  if (type === 'edit') {
    info['id'] = id.value;
    return await updateMenus(info);
  } else {
    console.log('错误方式');
    return {data: '错误方式'};
  }
};

// 删除菜单
const confirmDel = async (record) => {
  let res = await delMenus({id: record.id})
  if (!res) return;
  await getAllMenus()
  message.success(res.data)
}

// 重置表单
const restForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 表单规则
const rules = {
  path: {
    required: true,
    message: "请输入路由地址",
    trigger: "change",
  },
  component: {
    required: true,
    message: "请输入组件地址",
    trigger: "change",
  },
  label: {
    required: true,
    message: "请输入菜单名称",
    trigger: "change",
  }
}

// 表格
const data = ref([]);
const columns = [
  {
    title: '名称',
    dataIndex: 'label',
    key: 'label',
  },
  {
    title: '图标',
    dataIndex: 'icon',
    key: 'icon',
  },
  {
    title: '父级菜单',
    dataIndex: 'parent_id',
    key: 'parent_id',
  },
  {
    title: '路由地址',
    dataIndex: 'path',
    key: 'path',
  },
  {
    title: '组件',
    dataIndex: 'component',
    key: 'component',
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
  },
  {
    title: '更新时间',
    dataIndex: 'update_time',
    key: 'update_time',
  }, {
    title: '描述',
    dataIndex: 'remark',
    key: 'remark',
  }, {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 150
  }
];

// 表格选中
const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },

});
const getCurrentStyle = current => {
  const style = {};
  if (current.date() === 1) {
    style.border = '1px solid #1890ff';
    style.borderRadius = '50%';
  }
  return style;
};

// 打开弹窗
const openModal = (type, record) => {
  restForm()
  switch (type) {
    case 'add':
      title.value = '新增菜单'
      break;
    case 'edit':
      title.value = '编辑菜单'
      id.value = record.id;
      handelReactiveData(formState, record);
      break;
    default:
      title.value = '提示'
      break;
  }
  ModalRef.value?.ToggleModal();
}

const handelReactiveData = (reactive, obj) => {
  for (const reactiveKey in reactive) {
    if (obj[reactiveKey]) reactive[reactiveKey] = obj[reactiveKey];
  }
}


//获取所有菜单
const getAllMenus = async () => {
  let res = await get_menus()
  if (res.status === 400) message.error(res.data)
  else {
    data.value = res.data.map((item, index) => {
      return {key: item.id, ...item}
    })
  }
}

onMounted(async () => {
  await getAllMenus()
})

</script>

<style lang="scss" scoped>
.tableHeader {
  width: 100%;
  display: flex;
  flex-direction: column;

  .search {
    .btn {
      display: flex;
      gap: 15px;
    }
  }

  .buttons {
    width: 100%;
    margin: 15px 0;
    display: flex;
    align-items: center;
    gap: 15px;
  }
}

</style>